﻿/*
--------------------------------------
File: RotateLicensePlate.cs
Project: Themaopdracht 7
Author: Maarten Kroon

Description:
Finds the angle and rotates the license plate
--------------------------------------
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace THO7_Team8
{
    class RotateLicensePlate : VisionAlgorithm
    {
        public RotateLicensePlate(String name) : base(name) { }
        public override System.Drawing.Bitmap DoAlgorithm(System.Drawing.Bitmap sourceImage)
        {
            Bitmap returnImage = new Bitmap(sourceImage);
            returnImage = rotateImage(returnImage, (float)findAngle(returnImage));            
            return returnImage;
        }

        public static Bitmap rotateImage(Bitmap b, float angle)
        {
            //create a new empty bitmap to hold rotated image
            Bitmap returnBitmap = new Bitmap(b.Width, b.Height);
            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(returnBitmap);
            //move rotation point to center of image
            g.TranslateTransform((float)b.Width / 2, (float)b.Height / 2);
            //rotate
            g.RotateTransform(angle);
            //move image back
            g.TranslateTransform(-(float)b.Width / 2, -(float)b.Height / 2);
            //draw passed in image onto graphics object
            g.DrawImage(b, new Point(0, 0));

            //Makes the Bitmap monochrome again to prevent the smoothing of the image
            returnBitmap = MyImage.makeMonochrome(returnBitmap);
            return returnBitmap;
        }

        //Finds the angle that the license plate needs to rotate
        public double findAngle(Bitmap image)
        {
            int width = image.Width;
            int[] array = MyImage.BmpToArray(image);

            //If the image is rotated to the left
            int overstaand = 0;
            if (array[0] == -16777216)
            {
                while (array[overstaand] == -16777216)
                {
                    overstaand += width;
                }
            }
            //If the image is rotated to the right
            else
            {
                while (array[overstaand - 1] == -16777216)
                {
                    overstaand += width;
                }
            }
            double douOverstaand = (double)overstaand / width;
            double angle = Math.Atan(douOverstaand / width);

            angle = angle * (180.0 / Math.PI);
            return angle;
        }
    }
}
